﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using ASPItalia.ModelVirtualCasting.WPF.Views;
using ASPItalia.ModelVirtualCasting.WPF.ViewModels;
using System.Windows.Shell;
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.IO.Packaging;
using ASPItalia.ModelVirtualCasting.WPF.Common.Messaging;

namespace ASPItalia.ModelVirtualCasting.WPF
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class MVCApp : Application
    {

        private static Mutex appMutex;
        private JumpList jumpList;

        public MVCApp()
        {
            WebRequest.RegisterPrefix("pack", new PackWebRequestFactory());
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            if (StartMutex(e.Args))
            {
                // Start listening remote tasks
                ViewModelsContext.Current.TaskbarViewModel.Listen();
                // Intercept when a new candidate il selected
                Messenger.Default.Register<PropertyChangedMessage<ModelViewModel>>(this, PropertyChanged);

                CreateJumpList();
            }
            else
            {
                this.Shutdown();
            }
        }

        private void CandidatesView_CurrentChanged(object sender, EventArgs e)
        {
        }

        private void CreateJumpList()
        {
            jumpList = new JumpList();
            JumpList.SetJumpList(this, jumpList);
        }

        private void PropertyChanged(PropertyChangedMessage<ModelViewModel> message)
        {
            if (message.PropertyName == "CurrentModel" && message.NewValue.IsNotNull())
            {   
                string appPath = Environment.CommandLine.Substring(1, Environment.CommandLine.Length - 3);

                // Remove old models
                while (jumpList.JumpItems.Count > 5)
                    jumpList.JumpItems.RemoveAt(jumpList.JumpItems.Count - 1);

                string arg = "ShowModel " + message.NewValue.GetHashCode();
                if (!jumpList.JumpItems.OfType<JumpTask>().Any(j => j.Arguments == arg))
                    jumpList.JumpItems.Insert(0, new JumpTask
                    {
                        Title = message.NewValue.FullName,
                        ApplicationPath = appPath,
                        Arguments = arg,
                    });

                jumpList.Apply();
            }
        }

        private bool StartMutex(string[] args)
        {
            bool createNew;
            // Ensure that only one application is running
            appMutex = new Mutex(false, "ModelVirtualCasting", out createNew);

            // Application already running
            if (!createNew)
            {
                if (args.Length > 0)
                {
                    if (args[0] == "ShowModel")
                    {
                        ViewModelsContext.Current.TaskbarViewModel.ShowModel(Convert.ToInt32(args[1]));
                    }
                }

                return false;
            }

            return true;
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            // Remove jump list
            JumpList.SetJumpList(this, null);

            appMutex.Close();
        }
    }

}
